package cre.tomcat7.ch00.startup;

import cre.tomcat7.ch00.core.SimpleEngine;
import org.apache.catalina.*;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.core.StandardServer;
import org.apache.catalina.core.StandardService;
import org.apache.catalina.startup.HostConfig;

/**
 * tomcat bootstrap
 *
 * @Author penglai
 * @Date 2017/1/4.
 */
public class Bootstrap {

    public static void main(String[] args) {
        prepare();
        Container container = createContainer();
        Connector connector = createConnector();

        Service service = new StandardService();
        service.setName("Stand-alone Service");

        service.setContainer(container);
        service.addConnector(connector);

        Server server = new StandardServer();
        server.addService(service);

        try {
            server.init();
            server.start();

            server.await();
//            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void prepare() {
        System.setProperty(Globals.CATALINA_HOME_PROP, System.getProperty("user.dir"));
        System.setProperty(Globals.CATALINA_BASE_PROP, System.getProperty("user.dir"));
    }

    private static Connector createConnector() {
        Connector connector = new Connector(gainProtocol());
        connector.setPort(8080);
        return connector;
    }

    private static String gainProtocol() {
        return "HTTP/1.1";
    }

    private static Container createContainer() {
        Engine engine = new SimpleEngine();
        engine.setName("Simple");
        engine.setDefaultHost("localhost");

        Host host = new StandardHost();
        host.setName("localhost");
        host.setAppBase("/Users/penglai/opt/webapps");

        host.setParentClassLoader(engine.getParentClassLoader());
        HostConfig hostConfig = new HostConfig();
        host.addLifecycleListener(hostConfig);

        engine.addChild(host);
        return engine;
    }
}
